package net.vkits.common.validators;

import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by ethan-liu on 16/6/9.
 */
public class IdCardNoValidator implements ConstraintValidator<IdCardNo, String> {
    @Override
    public void initialize(IdCardNo constraintAnnotation) {
        //初始化，得到注解数据
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (StringUtils.isEmpty(value)) {
            return true;
        }
        if (isIdCardNo(value)) {
            return new IDCard().verify(value);
        }
        return false;
    }

    private static boolean isIdCardNo(String idCardNo) {
        Pattern pattern = Pattern.compile("(^\\d{15}$)|(^\\d{17}([0-9]|X)$)");
        Matcher matcher = pattern.matcher(idCardNo);
        return matcher.matches();
    }
}
